/**
 * 主脚本文件
 * 处理页面交互、图表渲染和全局功能
 */
document.addEventListener('DOMContentLoaded', () => {
    console.log('页面加载完成，开始初始化...');

    // 等待配置加载完成后再初始化其他功能
    if (window.configManager) {
        window.configManager.loadConfig().then(() => {
            initializeWithConfig();
        });
    } else {
        // 如果配置管理器未加载，使用默认初始化
        initializeWithConfig();
    }
});

function initializeWithConfig() {
    // 初始化日期时间显示
    initDateTime();

    // 初始化打字机效果
    initTypingEffect();

    // 初始化项目过滤器
    initProjectFilter();

    // 初始化导航切换
    initNavigation();

    // 延迟初始化雷达图，确保Chart.js加载完成
    setTimeout(() => {
        if (document.querySelector('.page.active')?.id === 'resume') {
            initSkillsRadar();
        }
    }, 1000);

    // 初始化技能树
    if (document.querySelector('.page.active')?.id === 'learning') {
        initSkillTree();
    }

    // 初始化代码高亮
    initCodeHighlight();

    // 只在配置页面激活时初始化配置相关功能
    if (document.querySelector('.page.active')?.id === 'config') {
        // 初始化主题配置
        initThemeConfig();

        // 初始化布局编辑器
        initLayoutEditor();

        // 初始化配置导入/导出
        initConfigIO();
    }

    // 添加模块边框呼吸效果
    initPulseBorders();

    // 初始化移动端适配
    initMobileAdaptation();

    // 初始化学习页面功能
    initLearningPage();
});

/**
 * 初始化学习页面功能
 */
function initLearningPage() {
    // 笔记展开/收起功能
    const viewNoteButtons = document.querySelectorAll('.view-note');
    const closeNoteButtons = document.querySelectorAll('.close-note');

    viewNoteButtons.forEach(button => {
        button.addEventListener('click', () => {
            const noteId = button.dataset.noteId;
            const preview = button.closest('.note-item').querySelector('.note-preview');
            const fullContent = document.getElementById(`note-${noteId}`);

            if (preview && fullContent) {
                preview.style.display = 'none';
                fullContent.style.display = 'block';
            }
        });
    });

    closeNoteButtons.forEach(button => {
        button.addEventListener('click', () => {
            const noteId = button.dataset.noteId;
            const preview = button.closest('.note-item').querySelector('.note-preview');
            const fullContent = document.getElementById(`note-${noteId}`);

            if (preview && fullContent) {
                preview.style.display = 'block';
                fullContent.style.display = 'none';
            }
        });
    });
}

/**
 * 初始化移动端适配
 */
function initMobileAdaptation() {
    // 检测设备类型
    const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;

    if (isMobile) {
        document.body.classList.add('mobile-device');
    }

    if (isTablet) {
        document.body.classList.add('tablet-device');
    }

    // 窗口大小变化时重新渲染图表
    let resizeTimer;
    window.addEventListener('resize', () => {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(() => {
            // 重新初始化雷达图
            if (document.querySelector('.page.active')?.id === 'resume') {
                initSkillsRadar();
            }

            // 重新初始化技能树
            if (document.querySelector('.page.active')?.id === 'learning') {
                initSkillTree();
            }
        }, 300);
    });

    // 移动端触摸优化
    if (isMobile) {
        // 禁用项目卡片的悬停翻转效果，改为点击翻转
        const projectCards = document.querySelectorAll('.project-card');
        projectCards.forEach(card => {
            let isFlipped = false;
            card.addEventListener('click', (e) => {
                e.preventDefault();
                const cardInner = card.querySelector('.card-inner');
                if (isFlipped) {
                    cardInner.style.transform = 'rotateY(0deg)';
                    isFlipped = false;
                } else {
                    cardInner.style.transform = 'rotateY(180deg)';
                    isFlipped = true;
                }
            });

            // 禁用悬停效果
            card.style.pointerEvents = 'auto';
            card.addEventListener('mouseenter', (e) => {
                e.preventDefault();
            });
        });

        // 优化滚动性能
        document.addEventListener('touchstart', () => { }, { passive: true });
        document.addEventListener('touchmove', () => { }, { passive: true });
    }

    // 处理横屏/竖屏切换
    window.addEventListener('orientationchange', () => {
        setTimeout(() => {
            // 重新计算布局
            if (document.querySelector('.page.active')?.id === 'resume') {
                initSkillsRadar();
            }
        }, 500);
    });
}

/**
 * 初始化导航切换功能
 */
function initNavigation() {
    const navItems = document.querySelectorAll('.main-nav li');
    const pages = document.querySelectorAll('.page');

    navItems.forEach(item => {
        item.addEventListener('click', () => {
            const targetPage = item.dataset.page;

            // 更新导航状态
            navItems.forEach(nav => nav.classList.remove('active'));
            item.classList.add('active');

            // 切换页面
            pages.forEach(page => {
                page.classList.remove('active');
                if (page.id === targetPage) {
                    page.classList.add('active');

                    // 根据不同页面初始化相应功能
                    if (targetPage === 'resume') {
                        // 如果切换到简历页面，重新初始化雷达图
                        setTimeout(() => {
                            initSkillsRadar();
                        }, 100);
                    } else if (targetPage === 'config') {
                        // 如果切换到配置页面，初始化配置相关功能
                        initThemeConfig();
                        initLayoutEditor();
                        initConfigIO();
                    } else if (targetPage === 'learning') {
                        // 如果切换到学习页面，初始化技能树
                        initSkillTree();
                    }
                }
            });
        });
    });
}

/**
 * 初始化日期时间显示
 */
function initDateTime() {
    const dateTimeElement = document.getElementById('date-time');
    if (dateTimeElement) {
        const updateDateTime = () => {
            const now = new Date();
            const options = {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            };
            dateTimeElement.textContent = now.toLocaleString('zh-CN', options);
        };

        // 立即更新一次
        updateDateTime();

        // 每分钟更新一次
        setInterval(updateDateTime, 60000);
    }
}

/**
 * 初始化打字机效果
 */
function initTypingEffect() {
    const commandPrompt = document.querySelector('.command-prompt');
    if (commandPrompt) {
        const messages = [
            '正在扫描系统漏洞...',
            '正在分析网络流量...',
            '正在破解加密算法...',
            '正在编译量子代码...',
            '正在部署神经网络...'
        ];

        let currentIndex = 0;

        const typeNextMessage = () => {
            const message = messages[currentIndex];
            const typingElement = document.createElement('span');
            typingElement.className = 'typing-animation';
            commandPrompt.innerHTML = '> ';
            commandPrompt.appendChild(typingElement);

            let charIndex = 0;
            const typeChar = () => {
                if (charIndex < message.length) {
                    typingElement.textContent += message.charAt(charIndex);
                    charIndex++;
                    setTimeout(typeChar, 50 + Math.random() * 50);
                } else {
                    // 完成当前消息后，准备下一条
                    setTimeout(() => {
                        currentIndex = (currentIndex + 1) % messages.length;
                        typeNextMessage();
                    }, 3000);
                }
            };

            typeChar();
        };

        // 开始打字效果
        typeNextMessage();
    }
}

/**
 * 初始化项目过滤器
 */
function initProjectFilter() {
    const filterTags = document.querySelectorAll('.filter-tags .tag');
    const projectCards = document.querySelectorAll('.project-card');

    filterTags.forEach(tag => {
        tag.addEventListener('click', () => {
            // 更新活动标签
            filterTags.forEach(t => t.classList.remove('active'));
            tag.classList.add('active');

            const filter = tag.dataset.filter;

            // 过滤项目卡片
            projectCards.forEach(card => {
                if (filter === 'all' || card.dataset.category === filter) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        });
    });
}

/**
 * 初始化技能雷达图
 */
function initSkillsRadar() {
    console.log('开始初始化雷达图...');
    const radarCanvas = document.getElementById('skills-radar');

    if (!radarCanvas) {
        console.error('找不到雷达图canvas元素');
        return;
    }

    console.log('找到canvas元素:', radarCanvas);
    console.log('Chart.js是否可用:', !!window.Chart);

    // 确保canvas可见
    const container = radarCanvas.closest('.radar-chart-container');
    if (container) {
        container.style.display = 'block';
        container.style.visibility = 'visible';
    }

    // 设置canvas尺寸 - 响应式适配
    const containerWidth = radarCanvas.parentElement.clientWidth || 400;
    const containerHeight = radarCanvas.parentElement.clientHeight || 300;
    const isMobile = window.innerWidth <= 768;

    // 根据屏幕大小调整canvas尺寸
    let canvasWidth, canvasHeight;
    if (isMobile) {
        canvasWidth = Math.min(containerWidth - 20, window.innerWidth - 40);
        canvasHeight = Math.min(canvasWidth * 0.75, 250); // 移动端高度限制
    } else {
        canvasWidth = Math.min(containerWidth, 400);
        canvasHeight = Math.min(containerHeight, 300);
    }

    radarCanvas.width = canvasWidth;
    radarCanvas.height = canvasHeight;
    radarCanvas.style.width = canvasWidth + 'px';
    radarCanvas.style.height = canvasHeight + 'px';

    console.log('Canvas尺寸设置为:', radarCanvas.width, 'x', radarCanvas.height);

    const ctx = radarCanvas.getContext('2d');

    if (window.Chart) {
        console.log('使用Chart.js绘制雷达图');

        // 清除之前的图表实例
        if (window.skillsRadarChart) {
            window.skillsRadarChart.destroy();
        }

        // 定义技能数据
        const skillsData = {
            labels: ['前端开发', '后端开发', '游戏设计', '数据可视化', '人工智能', 'UI/UX设计'],
            datasets: [{
                label: '技能水平',
                data: [90, 75, 85, 80, 70, 65],
                backgroundColor: 'rgba(0, 247, 255, 0.2)',
                borderColor: 'rgba(0, 247, 255, 1)',
                pointBackgroundColor: 'rgba(0, 247, 255, 1)',
                pointBorderColor: '#fff',
                pointHoverBackgroundColor: '#fff',
                pointHoverBorderColor: 'rgba(0, 247, 255, 1)',
                borderWidth: 2,
                pointRadius: 4
            }]
        };

        // 雷达图配置
        const config = {
            type: 'radar',
            data: skillsData,
            options: {
                responsive: false,
                maintainAspectRatio: false,
                scales: {
                    r: {
                        beginAtZero: true,
                        max: 100,
                        min: 0,
                        ticks: {
                            display: false, // 隐藏刻度标签
                            stepSize: 20,
                            backdropColor: 'transparent', // 移除背景色
                            color: 'transparent' // 隐藏刻度文字
                        },
                        grid: {
                            color: 'rgba(255, 255, 255, 0.1)',
                            lineWidth: 1
                        },
                        angleLines: {
                            color: 'rgba(255, 255, 255, 0.1)',
                            lineWidth: 1
                        },
                        pointLabels: {
                            color: '#e0e0e0',
                            font: {
                                family: "'Fira Code', 'Courier New', monospace",
                                size: isMobile ? 9 : 11
                            },
                            padding: isMobile ? 5 : 10
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        enabled: true,
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        titleColor: '#00f7ff',
                        bodyColor: '#e0e0e0',
                        borderColor: '#00f7ff',
                        borderWidth: 1
                    }
                },
                elements: {
                    line: {
                        borderWidth: 2
                    },
                    point: {
                        radius: 4,
                        hoverRadius: 6
                    }
                }
            }
        };

        try {
            // 创建雷达图
            window.skillsRadarChart = new Chart(ctx, config);
            console.log('Chart.js雷达图创建成功');
        } catch (error) {
            console.error('Chart.js雷达图创建失败:', error);
            // 如果Chart.js失败，绘制简单的雷达图
            drawSimpleRadar(ctx, radarCanvas.width, radarCanvas.height);
        }
    } else {
        console.log('Chart.js不可用，使用简单雷达图');
        // 如果没有Chart.js，绘制简单的雷达图
        drawSimpleRadar(ctx, radarCanvas.width, radarCanvas.height);
    }
}

/**
 * 绘制简单的雷达图（备用方案）
 */
function drawSimpleRadar(ctx, width = 400, height = 300) {
    const centerX = width / 2;
    const centerY = height / 2;
    const maxRadius = Math.min(width, height) / 3;

    // 技能数据
    const skills = [
        { name: '前端开发', value: 90 },
        { name: '后端开发', value: 75 },
        { name: '游戏设计', value: 85 },
        { name: '数据可视化', value: 80 },
        { name: '人工智能', value: 70 },
        { name: 'UI/UX设计', value: 65 }
    ];

    const angleStep = (Math.PI * 2) / skills.length;

    // 清空画布
    ctx.clearRect(0, 0, width, height);

    // 绘制网格线
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
    ctx.lineWidth = 1;

    // 绘制同心圆
    for (let i = 1; i <= 5; i++) {
        ctx.beginPath();
        ctx.arc(centerX, centerY, (maxRadius / 5) * i, 0, Math.PI * 2);
        ctx.stroke();
    }

    // 绘制轴线
    for (let i = 0; i < skills.length; i++) {
        const angle = i * angleStep - Math.PI / 2;
        const x = centerX + Math.cos(angle) * maxRadius;
        const y = centerY + Math.sin(angle) * maxRadius;

        ctx.beginPath();
        ctx.moveTo(centerX, centerY);
        ctx.lineTo(x, y);
        ctx.stroke();

        // 绘制标签
        ctx.fillStyle = '#e0e0e0';
        const fontSize = width < 300 ? 9 : 11;
        ctx.font = `${fontSize}px "Fira Code", monospace`;
        ctx.textAlign = 'center';

        const labelPadding = width < 300 ? 15 : 20;
        const labelX = centerX + Math.cos(angle) * (maxRadius + labelPadding);
        const labelY = centerY + Math.sin(angle) * (maxRadius + labelPadding);
        ctx.fillText(skills[i].name, labelX, labelY);
    }

    // 绘制数据多边形
    ctx.beginPath();
    ctx.strokeStyle = 'rgba(0, 247, 255, 1)';
    ctx.fillStyle = 'rgba(0, 247, 255, 0.2)';
    ctx.lineWidth = 2;

    for (let i = 0; i < skills.length; i++) {
        const angle = i * angleStep - Math.PI / 2;
        const radius = (skills[i].value / 100) * maxRadius;
        const x = centerX + Math.cos(angle) * radius;
        const y = centerY + Math.sin(angle) * radius;

        if (i === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    }

    ctx.closePath();
    ctx.fill();
    ctx.stroke();

    // 绘制数据点
    ctx.fillStyle = 'rgba(0, 247, 255, 1)';
    for (let i = 0; i < skills.length; i++) {
        const angle = i * angleStep - Math.PI / 2;
        const radius = (skills[i].value / 100) * maxRadius;
        const x = centerX + Math.cos(angle) * radius;
        const y = centerY + Math.sin(angle) * radius;

        ctx.beginPath();
        ctx.arc(x, y, 4, 0, Math.PI * 2);
        ctx.fill();
    }

    console.log('简单雷达图绘制完成');
}

/**
 * 初始化技能树
 */
function initSkillTree() {
    const skillTreeCanvas = document.getElementById('skill-tree-canvas');
    if (skillTreeCanvas) {
        const ctx = skillTreeCanvas.getContext('2d');

        // 设置画布尺寸
        skillTreeCanvas.width = skillTreeCanvas.parentElement.clientWidth;
        skillTreeCanvas.height = 500;

        // 技能树节点数据
        const nodes = [
            { id: 1, x: skillTreeCanvas.width / 2, y: 50, label: '编程基础', level: 95, connections: [2, 3, 4] },
            { id: 2, x: skillTreeCanvas.width / 4, y: 150, label: '前端开发', level: 90, connections: [5, 6] },
            { id: 3, x: skillTreeCanvas.width / 2, y: 150, label: '后端开发', level: 75, connections: [7, 8] },
            { id: 4, x: skillTreeCanvas.width * 3 / 4, y: 150, label: '游戏开发', level: 85, connections: [9, 10] },
            { id: 5, x: skillTreeCanvas.width / 8, y: 250, label: 'HTML/CSS', level: 95, connections: [] },
            { id: 6, x: skillTreeCanvas.width * 3 / 8, y: 250, label: 'JavaScript', level: 90, connections: [11] },
            { id: 7, x: skillTreeCanvas.width * 5 / 8, y: 250, label: 'Node.js', level: 80, connections: [] },
            { id: 8, x: skillTreeCanvas.width * 7 / 8, y: 250, label: 'Python', level: 75, connections: [12] },
            { id: 9, x: skillTreeCanvas.width / 4, y: 350, label: 'Unity', level: 85, connections: [] },
            { id: 10, x: skillTreeCanvas.width / 2, y: 350, label: 'Unreal', level: 70, connections: [] },
            { id: 11, x: skillTreeCanvas.width * 3 / 8, y: 350, label: 'React', level: 85, connections: [] },
            { id: 12, x: skillTreeCanvas.width * 7 / 8, y: 350, label: 'TensorFlow', level: 65, connections: [] }
        ];

        // 绘制连接线
        ctx.strokeStyle = 'rgba(0, 247, 255, 0.5)';
        ctx.lineWidth = 2;

        nodes.forEach(node => {
            node.connections.forEach(targetId => {
                const target = nodes.find(n => n.id === targetId);
                if (target) {
                    // 绘制连接线
                    ctx.beginPath();
                    ctx.moveTo(node.x, node.y);
                    ctx.lineTo(target.x, target.y);
                    ctx.stroke();
                }
            });
        });

        // 绘制节点
        nodes.forEach(node => {
            // 节点大小基于技能水平
            const radius = 20 + (node.level / 10);

            // 绘制节点背景
            ctx.beginPath();
            ctx.arc(node.x, node.y, radius, 0, Math.PI * 2);
            ctx.fillStyle = `rgba(0, 247, 255, ${node.level / 100})`;
            ctx.fill();

            // 绘制节点边框
            ctx.beginPath();
            ctx.arc(node.x, node.y, radius, 0, Math.PI * 2);
            ctx.strokeStyle = 'rgba(0, 247, 255, 0.8)';
            ctx.lineWidth = 2;
            ctx.stroke();

            // 绘制节点标签
            ctx.fillStyle = '#e0e0e0';
            ctx.font = '12px "Fira Code", monospace';
            ctx.textAlign = 'center';
            ctx.fillText(node.label, node.x, node.y + radius + 15);

            // 绘制技能水平
            ctx.fillStyle = 'rgba(0, 247, 255, 1)';
            ctx.font = 'bold 12px "Fira Code", monospace';
            ctx.fillText(`${node.level}%`, node.x, node.y + 4);
        });
    }
}

/**
 * 初始化代码高亮
 */
function initCodeHighlight() {
    if (window.hljs) {
        document.querySelectorAll('pre code').forEach(block => {
            hljs.highlightBlock(block);
        });
    }
}

/**
 * 初始化主题配置
 */
function initThemeConfig() {
    const colorOptions = document.querySelectorAll('.color-option');

    colorOptions.forEach(option => {
        option.addEventListener('click', () => {
            // 更新活动状态
            colorOptions.forEach(opt => opt.classList.remove('active'));
            option.classList.add('active');

            // 更新强调色
            const color = option.dataset.color;
            document.documentElement.style.setProperty('--accent-color', color);
        });
    });

    // 初始化滑块控制
    initSliders();
}

/**
 * 初始化滑块控制
 */
function initSliders() {
    // 数字雨密度滑块
    const rainDensitySlider = document.getElementById('rain-density');
    if (rainDensitySlider) {
        const rangeValue = rainDensitySlider.parentElement.querySelector('.range-value');

        // 设置初始值显示
        if (rangeValue) {
            rangeValue.textContent = rainDensitySlider.value;
        }

        rainDensitySlider.addEventListener('input', (e) => {
            const value = e.target.value;
            if (rangeValue) {
                rangeValue.textContent = value;
            }

            // 更新数字雨密度
            if (window.matrixRain && window.matrixRain.setDensity) {
                window.matrixRain.setDensity(parseInt(value));
            }
        });
    }

    // 动画速度滑块
    const animationSpeedSlider = document.getElementById('animation-speed');
    if (animationSpeedSlider) {
        const rangeValue = animationSpeedSlider.parentElement.querySelector('.range-value');

        // 设置初始值显示
        if (rangeValue) {
            rangeValue.textContent = animationSpeedSlider.value;
        }

        animationSpeedSlider.addEventListener('input', (e) => {
            const value = e.target.value;
            if (rangeValue) {
                rangeValue.textContent = value;
            }

            // 更新动画速度
            if (window.effectsSystem) {
                window.effectsSystem.animationSpeed = parseInt(value);
            }

            // 更新CSS变量以影响全局动画速度
            document.documentElement.style.setProperty('--animation-speed-factor', 11 - parseInt(value));
        });
    }

    // 故障效果频率滑块
    const glitchFrequencySlider = document.getElementById('glitch-frequency');
    if (glitchFrequencySlider) {
        const rangeValue = glitchFrequencySlider.parentElement.querySelector('.range-value');

        // 设置初始值显示
        if (rangeValue) {
            rangeValue.textContent = glitchFrequencySlider.value;
        }

        glitchFrequencySlider.addEventListener('input', (e) => {
            const value = e.target.value;
            if (rangeValue) {
                rangeValue.textContent = value;
            }

            // 更新故障频率
            if (window.effectsSystem) {
                window.effectsSystem.glitchFrequency = parseInt(value);
            }
        });
    }

    // 添加测试按钮功能
    addTestButtons();
}

/**
 * 添加测试按钮功能
 */
function addTestButtons() {
    // 为主题设置面板添加测试按钮
    const themePanel = document.querySelector('.config-panel h3');
    if (themePanel && themePanel.textContent === '主题设置') {
        const testButton = document.createElement('button');
        testButton.className = 'btn btn-small';
        testButton.textContent = '测试故障效果';
        testButton.style.marginLeft = '1rem';
        testButton.style.fontSize = '0.8rem';
        testButton.style.padding = '0.3rem 0.6rem';

        testButton.addEventListener('click', () => {
            if (window.effectsSystem) {
                window.effectsSystem.triggerManualGlitch();
            }
        });

        themePanel.appendChild(testButton);
    }
}

/**
 * 初始化布局编辑器
 */
function initLayoutEditor() {
    const layoutItems = document.querySelectorAll('.layout-item');
    const layoutEditor = document.querySelector('.layout-editor');

    if (layoutItems && layoutEditor) {
        layoutItems.forEach(item => {
            // 拖拽开始
            item.addEventListener('dragstart', (e) => {
                e.dataTransfer.setData('text/plain', item.dataset.module);
                item.classList.add('dragging');
                layoutEditor.classList.add('drag-over');
            });

            // 拖拽结束
            item.addEventListener('dragend', () => {
                item.classList.remove('dragging');
                layoutEditor.classList.remove('drag-over');
            });
        });

        // 拖拽进入编辑器区域
        layoutEditor.addEventListener('dragenter', (e) => {
            e.preventDefault();
            layoutEditor.classList.add('drag-over');
        });

        // 拖拽离开编辑器区域
        layoutEditor.addEventListener('dragleave', (e) => {
            e.preventDefault();
            // 只有当拖拽完全离开编辑器时才移除样式
            if (!layoutEditor.contains(e.relatedTarget)) {
                layoutEditor.classList.remove('drag-over');
            }
        });

        // 允许放置
        layoutEditor.addEventListener('dragover', (e) => {
            e.preventDefault();
        });

        // 处理放置
        layoutEditor.addEventListener('drop', (e) => {
            e.preventDefault();
            layoutEditor.classList.remove('drag-over');

            const moduleId = e.dataTransfer.getData('text/plain');

            // 获取所有项目
            const items = Array.from(layoutEditor.querySelectorAll('.layout-item'));

            // 找到被拖动的项目
            const draggedItem = items.find(item => item.dataset.module === moduleId);

            if (!draggedItem) return;

            // 计算放置位置
            const y = e.clientY;
            const droppedPosition = items.findIndex(item => {
                if (item === draggedItem) return false;
                const box = item.getBoundingClientRect();
                return y < box.top + box.height / 2;
            });

            // 重新排序
            if (droppedPosition !== -1) {
                layoutEditor.insertBefore(draggedItem, items[droppedPosition]);
            } else {
                layoutEditor.appendChild(draggedItem);
            }

            // 添加成功反馈
            showLayoutUpdateFeedback();
        });
    }
}

/**
 * 显示布局更新反馈
 */
function showLayoutUpdateFeedback() {
    const feedback = document.createElement('div');
    feedback.textContent = '布局已更新';
    feedback.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background-color: rgba(0, 247, 255, 0.9);
        color: var(--bg-color);
        padding: 0.5rem 1rem;
        border-radius: 3px;
        font-family: var(--font-mono);
        font-size: 0.8rem;
        z-index: 1000;
        animation: fadeInOut 2s ease-in-out forwards;
    `;

    document.body.appendChild(feedback);

    setTimeout(() => {
        if (feedback.parentNode) {
            feedback.parentNode.removeChild(feedback);
        }
    }, 2000);
}

/**
 * 初始化配置导入/导出
 */
function initConfigIO() {
    const importBtn = document.getElementById('import-config');
    const exportBtn = document.getElementById('export-config');
    const configTextarea = document.getElementById('config-json');

    if (importBtn && exportBtn && configTextarea) {
        // 导出配置
        exportBtn.addEventListener('click', () => {
            const config = {
                theme: 'hacker',
                accentColor: getComputedStyle(document.documentElement).getPropertyValue('--accent-color').trim(),
                rainDensity: window.matrixRain ? window.matrixRain.density : 5,
                animationSpeed: window.effectsSystem ? window.effectsSystem.animationSpeed : 5,
                glitchFrequency: window.effectsSystem ? window.effectsSystem.glitchFrequency : 3
            };

            configTextarea.value = JSON.stringify(config, null, 2);
        });

        // 导入配置
        importBtn.addEventListener('click', () => {
            try {
                const config = JSON.parse(configTextarea.value);

                // 应用配置
                if (config.accentColor) {
                    document.documentElement.style.setProperty('--accent-color', config.accentColor);

                    // 更新颜色选择器
                    document.querySelectorAll('.color-option').forEach(option => {
                        if (option.dataset.color === config.accentColor) {
                            document.querySelectorAll('.color-option').forEach(opt => opt.classList.remove('active'));
                            option.classList.add('active');
                        }
                    });
                }

                // 更新雨密度
                if (config.rainDensity && window.matrixRain) {
                    window.matrixRain.setDensity(config.rainDensity);
                    const densitySlider = document.getElementById('rain-density');
                    if (densitySlider) {
                        densitySlider.value = config.rainDensity;
                        const rangeValue = densitySlider.parentElement.querySelector('.range-value');
                        if (rangeValue) {
                            rangeValue.textContent = config.rainDensity;
                        }
                    }
                }

                // 更新动画速度
                if (config.animationSpeed && window.effectsSystem) {
                    window.effectsSystem.animationSpeed = config.animationSpeed;
                    const speedSlider = document.getElementById('animation-speed');
                    if (speedSlider) {
                        speedSlider.value = config.animationSpeed;
                        const rangeValue = speedSlider.parentElement.querySelector('.range-value');
                        if (rangeValue) {
                            rangeValue.textContent = config.animationSpeed;
                        }
                    }
                }

                // 更新故障频率
                if (config.glitchFrequency && window.effectsSystem) {
                    window.effectsSystem.glitchFrequency = config.glitchFrequency;
                    const glitchSlider = document.getElementById('glitch-frequency');
                    if (glitchSlider) {
                        glitchSlider.value = config.glitchFrequency;
                        const rangeValue = glitchSlider.parentElement.querySelector('.range-value');
                        if (rangeValue) {
                            rangeValue.textContent = config.glitchFrequency;
                        }
                    }
                }

                // 触发一次故障效果作为反馈
                if (window.effectsSystem) {
                    window.effectsSystem.triggerManualGlitch();
                }

            } catch (error) {
                console.error('配置导入失败:', error);

                // 显示错误提示
                const errorMsg = document.createElement('div');
                errorMsg.textContent = '配置格式错误，请检查JSON语法';
                errorMsg.style.color = '#ff0000';
                errorMsg.style.fontSize = '0.8rem';
                errorMsg.style.marginTop = '0.5rem';

                const parent = configTextarea.parentElement;

                // 移除之前的错误消息
                const oldError = parent.querySelector('.error-msg');
                if (oldError) {
                    parent.removeChild(oldError);
                }

                errorMsg.className = 'error-msg';
                parent.appendChild(errorMsg);

                // 3秒后自动消失
                setTimeout(() => {
                    if (errorMsg.parentNode) {
                        errorMsg.parentNode.removeChild(errorMsg);
                    }
                }, 3000);
            }
        });
    }
}

/**
 * 初始化模块边框呼吸效果
 */
function initPulseBorders() {
    const elements = document.querySelectorAll('.terminal-welcome, .stat-box, .recent-activity, .project-card, .timeline-content, .notes-section, .skill-tree, .config-panel');

    elements.forEach(element => {
        element.classList.add('pulse-border');
    });
}